﻿using Easy.Common.Helper.JWT;
using Easy.Common.Results;
using Easy.Services.DbContexts;
using Easy.Services.Entities;
using Easy.Services.Interface;
using System.Linq.Expressions;

namespace Easy.Services.Core
{
    internal class CompanyService : ICompanyService
    {
        public long Add(Company company)
        {
            using MySQLDbContext db = new();
            BaseService<Company> baseService = new(db);
            return baseService.AddBase(company);

        }

        public APIResult Update(Company company)
        {
            using MySQLDbContext db = new();
            BaseService<Company> baseService = new(db);
            APIResult result = new()
            {
                Message = "更新失败"
            };
            var model = Get(r => r.Id == company.Id);
            if (model == null)
            {
                result.Message = "部门不存在";
                return result;
            }
            company.CreaterDate = model.CreaterDate;
            company.CreaterId = model.CreaterId;
            company.CreaterName = model.CreaterName;
            var res = baseService.UpdateBase(company);
            if (res)
            {
                result.Success = res;
                result.Message = "更新成功";
            }
            return result;

        }

        public Company Get(Expression<Func<Company, bool>> expression)
        {
            using MySQLDbContext db = new();
            BaseService<Company> baseService = new(db);
            return baseService.GetBase(expression);

        }

        public APIResult Delete(long id, TokenModelJwt tokenModel)
        {
            using MySQLDbContext db = new();
            BaseService<Company> baseService = new(db);
            APIResult result = new() { Message = "更新失败" };
            var model = Get(r => r.Id == id);
            if (model == null)
            {
                result.Message = "部门不存在";
                return result;
            }
            model.EditDate = DateTime.Now;
            model.EditId = tokenModel.Id;
            model.EditName = tokenModel.UserName;
            model.SetDelete();
            var res = baseService.UpdateBase(model);
            if (res)
            {
                result.Success = res;
                result.Message = "更新成功";
            }
            return result;

        }


        public List<Company> GetList()
        {
            using MySQLDbContext db = new();
            BaseService<Company> baseService = new(db);
            return baseService.GetList();

        }

        public bool Exist(Expression<Func<Company, bool>> expression)
        {
            using MySQLDbContext db = new();
            BaseService<Company> baseService = new(db);
            return baseService.Exist(expression);

        }


    }
}
